class Match < ActiveRecord::Base
  
  belongs_to :user
  has_one :score
  
  attr_accessor :match_players # contains the users string which we will parse to understand who is playing
  
  def my_best_scores_against_each_oponent_played
    
  end
  
  def leader_board
    
  end
  
  after_update :do_score
  
  def do_score
    @s = Score.new()
    @s.match_id = self.id
    if self.score_a > self.score_b
      @s.winner_id = self.user_id
      @s.looser_id = self.oponent_id
      @s.score = self.score_a.to_i      
      @s.save!
    elsif self.score_a < self.score_b
      @s.winner_id = self.oponent_id
      @s.looser_id = self.user_id
      @s.score = self.score_b.to_i      
      @s.save!
    else # draw do we care?
      
    end
    
    if league_game
      do_league_game_score
    end
  end
  
  def do_league_game_score
    # check that the players haven't already recorded this match
    
    
    # score the game
    # win = 3 pts
    # draw = 1 pts
    # loss = 0 pts
    if self.score_a > self.score_b # i won she lost
      
      @league_game_player_a = LeagueResults.find_or_create_by_player_id(self.user_id)
      @league_game_player_b = LeagueResults.find_or_create_by_player_id(self.oponent_id)
      
      @league_game_player_a.win = @league_game_player_a.win + 1
      @league_game_player_a.played = @league_game_player_a.played + 1
      @league_game_player_a.points = @league_game_player_a.points + 3
      
      @league_game_player_b.loss = @league_game_player_b.loss + 1
      @league_game_player_b.played = @league_game_player_b.played + 1

    elsif self.score_a < self.score_b # i lost she won
      
      @league_game_player_a = LeagueResults.find_or_create_by_player_id(self.oponent_id)
      @league_game_player_b = LeagueResults.find_or_create_by_player_id(self.user_id)
      
      @league_game_player_b.win     = @league_game_player_b.win + 1
      @league_game_player_b.played  = @league_game_player_b.played + 1
      @league_game_player_b.points  = @league_game_player_b.points + 3
      
      @league_game_player_a.loss    = @league_game_player_a.loss + 1
      @league_game_player_a.played  = @league_game_player_a.played + 1  
          
    else # draw
      @league_game_player_a = LeagueResults.find_or_create_by_player_id(self.user_id)
      @league_game_player_b = LeagueResults.find_or_create_by_player_id(self.oponent_id)
      

      @league_game_player_a.played = @league_game_player_a.played + 1
      @league_game_player_a.points = @league_game_player_a.points + 1
      
      @league_game_player_b.played = @league_game_player_b.played + 1
      @league_game_player_b.points = @league_game_player_b.points + 1
      
    end
    
    @league_game_player_a.league_id = @league_game_player_b.league_id = 1
    
    @league_game_player_a.save!
    @league_game_player_b.save!
  end
  
end
